import json
from gis.common import track_logging
import time

import requests
from requests import RequestException

from gis.common.exceptions import BizException
from gis.common.retry import retry
from itpay.core.recharge_order.const import *
from itpay.core.recharge_order.errors import ERROR_TONGLUEYUN_ERROR

_LOGGER = track_logging.getLogger(__name__)


@retry(RequestException)
def create_special_amount_order(order_id, bank_flag, card_number, amount):
    """
    根据特殊金额去匹配
    :param order_id: 秒付平台里的订单id
    :param bank_flag:收款卡的银行代码。是大陆的各个银行代码
    :param card_number: 收款卡的卡号
    :param amount:单位分，付的金额， 必须为数字，不能四舍五入，会严格检查金额是否匹配
    :return:
     "order_id","bank_flag", "card_number","amount", "create_time", “bank_name”, “card_login_name”
    """
    order_params = {
        "apikey": TONGLUE_CONF['SPECIAL_AMOUNT_CONF']['key'],
        "order_id": order_id,
        "bank_flag": bank_flag,
        "card_number": card_number,
        "amount": float(amount / 100),
        "create_time": time.time(),
        # "bank_name": "中国农业银行",  # 接口文档为必填项，经测试可以不填
        "card_login_name": "wu142018",  # 接口文档为必填项，经测试可以随便填
        "meta_data": {"QuickOrder": "Alipay2Bank"}  # 接口文档为必填项，经测试可以随便填
        # "meta_data": {"QuickOrder": "WX2Bank"}
    }

    _LOGGER.info(
        'tonglue create order {} {}'.format(TONGLUE_CONF['SPECIAL_AMOUNT_CONF']['create_order_url'], order_params))
    response = requests.post(TONGLUE_CONF['SPECIAL_AMOUNT_CONF']['create_order_url'],
                             headers={'Content-type': 'application/json', 'Accept': 'text/plain'},
                             data=json.dumps(order_params), timeout=5)
    _LOGGER.info('tonglue order_id: {}, resp: {} {}'.format(order_id, response.status_code, response.content))

    res = json.loads(response.content)
    success = res.get('success')
    if not success:
        raise BizException(ERROR_TONGLUEYUN_ERROR)
    return res['id']


@retry(RequestException)
def create_pay_info_order(order_id, bank_flag, card_number, amount, pay_account_num, pay_account_username):
    """
    根据特支付信息去匹配

    """
    order_params = {
        "apikey": TONGLUE_CONF['PAY_INFO_CONF']['key'],
        "order_id": order_id,
        "bank_flag": bank_flag,
        "card_login_name": "wu142018",
        "card_number": card_number,
        # "pay_card_number": pay_account_num,
        "pay_username": pay_account_username,
        "amount": float(amount / 100),
        "create_time": time.time(),
        "comment": "",
    }

    _LOGGER.info('tonglue create order {} {}'.format(TONGLUE_CONF['PAY_INFO_CONF']['create_order_url'], order_params))
    response = requests.post(TONGLUE_CONF['PAY_INFO_CONF']['create_order_url'],
                             headers={'Content-type': 'application/json', 'Accept': 'text/plain'},
                             data=json.dumps(order_params), timeout=5)
    _LOGGER.info('tonglue order_id: {}, {}'.format(response.status_code, response.content))

    _LOGGER.info('tonglue order_id: {}, resp: {} {}'.format(order_id, response.status_code, response.content))

    res = json.loads(response.content)
    success = res.get('success')
    if not success:
        raise BizException(ERROR_TONGLUEYUN_ERROR)
    return res['id']


@retry(RequestException)
def revoke_order(order_id):
    """
    撤销订单，通略云不能自动过期
    :param order_id:
    :return:
    """
    order_params = {
        "apikey": TONGLUE_CONF['SPECIAL_AMOUNT_CONF']['key'],
        "id": order_id,
    }

    _LOGGER.info(
        'tonglue create order {} {}'.format(TONGLUE_CONF['SPECIAL_AMOUNT_CONF']['revoke_order_url'], order_params))
    response = requests.post(TONGLUE_CONF['SPECIAL_AMOUNT_CONF']['revoke_order_url'],
                             headers={'Content-type': 'application/json', 'Accept': 'text/plain'},
                             data=json.dumps(order_params), timeout=5)
    _LOGGER.info('tonglue order_id: {}, resp: {} {}'.format(order_id, response.status_code, response.content))

    res = json.loads(response.content)
    success = res.get('success')
    if success:
        return True
    return False
